package com.shallwead.bna.util.gcm;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.os.AsyncTask;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.google.analytics.tracking.android.GoogleAnalytics;
import com.google.analytics.tracking.android.Tracker;
import com.shallwead.bna.BnA;
import com.shallwead.bna.Async.PushCircleAsync;
import com.shallwead.bna.Async.PushDialogAsync;
import com.shallwead.bna.Async.PushNotiAsync;
import com.shallwead.bna.object.AdGcmMsg;
import com.shallwead.bna.object.GCM;
import com.shallwead.bna.util.Constants;
import com.shallwead.bna.util.SharedPreferenceUtil;

public class GCM_Utils {

	public static void RegisterDevice(Context mContext, GCM mGCM) {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpPost request = new HttpPost(Constants.GCM_URL);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("id", mGCM.getId()));
			nameValuePairs.add(new BasicNameValuePair("udid", mGCM.getUdid()));
			nameValuePairs.add(new BasicNameValuePair("pkg", mGCM.getPkg()));
			request.setEntity(new UrlEncodedFormEntity(nameValuePairs,
					HTTP.UTF_8));
			HttpResponse response = client.execute(request);
			InputStream content = response.getEntity().getContent();
			Header contentEncoding = response.getEntity().getContentEncoding();
			if (contentEncoding != null
					&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
				content = new GZIPInputStream(content);
			}
			StringBuilder json = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					content, "utf-8"));
			String line = reader.readLine();
			while (line != null) {
				json.append(line);
				line = reader.readLine();
			}

			SharedPreferenceUtil.putbooleanSharedPreference(
					mContext.getApplicationContext(), "isGCM", true);
			Log.e("DayTrader", "isGCM == true");

		} catch (Exception e) {
			Log.e("DayTrader", "Exception getting JSON data", e);
			SharedPreferenceUtil.putbooleanSharedPreference(mContext, "isGCM",
					false);
		}
	}

	public static void init_GCM(Context mContext) {
		com.google.android.gcm.GCMRegistrar.checkDevice(mContext);
		com.google.android.gcm.GCMRegistrar.checkManifest(mContext);
		boolean isGCM = SharedPreferenceUtil.getbooleanSharedPreference(
				mContext, "isGCM");
		String regId = com.google.android.gcm.GCMRegistrar
				.getRegistrationId(mContext);
		if (!isGCM && regId.equals("")) {
			com.google.android.gcm.GCMRegistrar.register(mContext,
					BnA.GCM_Project_Number);
		}

	}

	public static void init_Anal(Context mContext) {
		GoogleAnalytics mGaInstance = GoogleAnalytics.getInstance(mContext);
		Tracker mGaTracker = mGaInstance
				.getTracker(BnA.Analytics_Project_Number);
		mGaInstance.setDefaultTracker(mGaTracker);
		mGaTracker.sendView("/HomeScreen");
	}

	public static class RegisterDevice extends AsyncTask<GCM, Void, Boolean> {
		Context mContext;

		RegisterDevice(Context mContext) {
			this.mContext = mContext;
		}

		@Override
		protected Boolean doInBackground(GCM... params) {
			GCM_Utils.RegisterDevice(mContext, params[0]);
			return true;
		}
	}

	public static void setNotiType(Context mContext, AdGcmMsg gcmMsg) {
		// noti
		if ("1".equals(gcmMsg.getNotiType())) {
			setPushNotiBar(mContext, gcmMsg);
		}
		// pop up
		else if ("2".equals(gcmMsg.getNotiType())) {
			setPushPopup(mContext, gcmMsg);
		}
		// dance
		else if ("3".equals(gcmMsg.getNotiType())) {
			setPushDance(mContext, gcmMsg);
		}
	}

	public static void setPushNotiBar(Context mContext, AdGcmMsg gcmMsg) {
		try {
			startPushNotiBar(mContext, gcmMsg);
		} catch (Exception e) {
		}
	}

	public static void setPushPopup(Context mContext, AdGcmMsg gcmMsg) {
		startPushPopup(mContext, gcmMsg);
	}

	public static void setPushDance(Context mContext, AdGcmMsg gcmMsg) {
		startPushCircleService(mContext, gcmMsg);
	}

	public static void startPushNotiBar(Context mContext, AdGcmMsg gcmMsg) {
		new PushNotiAsync(mContext).execute();
	}

	public static void startPushPopup(Context mContext, AdGcmMsg gcmMsg) {
		new PushDialogAsync(mContext).execute();
	}

	public static void startPushCircleService(Context mContext, AdGcmMsg gcmMsg) {
		new PushCircleAsync(mContext).execute();

	}

	public static String getUDID(Context context) {
		String UDID = "";
		try {
			TelephonyManager tm = ((TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE));
			UDID = gID(tm, context);
			Log.e("UDID", UDID);
		} catch (Exception e) {
			UDID = "NOUDID";
		}
		return UDID;
	}

	public static String gID(TelephonyManager tm, Context context) {
		if (tm == null)
			return "NoTM_"
					+ Settings.Secure.getString(context.getContentResolver(),
							Settings.Secure.ANDROID_ID);
		else
			return ((tm.getDeviceId() != null) ? tm.getDeviceId() : "N")
					+ "_"
					+ ((tm.getSimSerialNumber() != null) ? tm
							.getSimSerialNumber() : "N")
					+ "_"
					+ Settings.Secure.getString(context.getContentResolver(),
							Settings.Secure.ANDROID_ID);
	}

}
